package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    private Socket socket;

    public Client() {
        try {
            System.out.println("正在连接服务器.....");
            socket = new Socket("localhost", 8088);
            System.out.println("与服务器建立连接！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() throws IOException {
        try {
            ServerHandler s = new ServerHandler();
            Thread t = new Thread(s);
            t.setDaemon(true);
            t.start();
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw, true);

            Scanner scan = new Scanner(System.in);
            pw.println("你好服务器！");
            while (true) {
                String str = scan.nextLine();
                pw.println(str);
                if (str.equals("exit")) {
                    break;
                }
            }
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            socket.close();
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        try {
            client.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private class ServerHandler implements Runnable {
        public void run() {
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String mes;
                while (((mes = br.readLine()) != null)&& !mes.equals("exit")) {
                    System.out.println(mes);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
